package com.example.localareanetworkchat.fragment.home.adapter

import android.content.Context
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.navigation.Navigation
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.localareanetworkchat.R
import com.example.localareanetworkchat.fragment.MainViewModel
import com.example.localareanetworkchat.persistence.entity.ChatGroup
import com.example.localareanetworkchat.persistence.entity.GroupAddType

class ChatGroupListAdapter(val context: Context, private val viewModel: MainViewModel) : ListAdapter<ChatGroup, ChatGroupListAdapter.MyViewHolder>(object :
    DiffUtil.ItemCallback<ChatGroup>() {
    override fun areItemsTheSame(oldItem: ChatGroup, newItem: ChatGroup): Boolean {
        return oldItem.id == newItem.id
    }

    override fun areContentsTheSame(oldItem: ChatGroup, newItem: ChatGroup): Boolean {
        return oldItem == newItem
    }

}) {

    val TAG = ChatGroupListAdapter::class.simpleName

    class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val tvGroupName: TextView = itemView.findViewById(R.id.tv_chat_group_name)
        val tvCreator: TextView = itemView.findViewById(R.id.tv_chat_group_creator)
        val tvCreateTime: TextView = itemView.findViewById(R.id.tv_chat_group_create_time)
        val tvInvitationCode: TextView = itemView.findViewById(R.id.tv_chat_group_invitation_code)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder = MyViewHolder(LayoutInflater.from(context).inflate(R.layout.chat_group_list_item, parent, false))

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        holder.tvGroupName.text = getItem(position).groupName
        holder.tvCreator.text = getItem(position).uid
        holder.tvCreateTime.text = getItem(position).createTime
        if (getItem(position).groupType == GroupAddType.GROUP_ADD_TYPE_CREATE){
            holder.tvInvitationCode.text = getItem(position).groupInvitationCode
        }else if (getItem(position).groupType == GroupAddType.GROUP_ADD_TYPE_JOIN){
            holder.tvInvitationCode.text = getItem(position).groupSubInvitationCode
        }

        holder.itemView.setOnClickListener {
            Log.i(TAG, "onBindViewHolder: click")
            viewModel.chatGroup = getItem(position)
            Navigation.findNavController(it).navigate(R.id.messageFragment)
        }
    }

}